package com.bw.lyc.mvp.view.mine;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.viewpager.widget.ViewPager;

import com.blankj.utilcode.util.LogUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bw.lyc.R;
import com.bw.lyc.mvp.base.model.BaseEntity;
import com.bw.lyc.mvp.base.view.BaseActivity;
import com.bw.lyc.mvp.contract.UpdateUserContract;
import com.bw.lyc.mvp.di.DaggerUpdateUserComponent;
import com.bw.lyc.mvp.di.UpdateUserModules;
import com.bw.lyc.mvp.model.UpdateUserModel;
import com.bw.lyc.mvp.model.db.DBManager;
import com.bw.lyc.mvp.model.db.UserEntityDao;
import com.bw.lyc.mvp.model.entity.UserEntity;
import com.bw.lyc.mvp.presenter.UpdateUserPresenter;
import com.bw.lyc.mvp.view.FrameActivity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class UpdateUserActivity extends BaseActivity<UpdateUserPresenter> implements View.OnClickListener, UpdateUserContract.IUpdateUserView {

    private ImageView viewTopBack;
    private RelativeLayout updateRl;
    private ImageView updateHeadImg;
    private RelativeLayout updateRl1;
    private TextView updateTv;
    private RelativeLayout updateRl2;
    private TextView updateTv1;
    private String path = "";
    private UpdateUserPresenter updateUserPresenter;
    private getUserBroadcast getUserBroadcast;
    private Intent intent;


    @Override
    public View addStatusView() {
        return f(R.id.update_user_relative);
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_update_user;
    }

    @Override
    public void initView() {
        requestPermissions(new String[]{
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA
        }, 101);
        viewTopBack = (ImageView) findViewById(R.id.view_top_back);
        updateRl = (RelativeLayout) findViewById(R.id.update_rl);
        updateHeadImg = (ImageView) findViewById(R.id.update_head_img);
        updateRl1 = (RelativeLayout) findViewById(R.id.update_rl1);
        updateTv = (TextView) findViewById(R.id.update_tv);
        updateRl2 = (RelativeLayout) findViewById(R.id.update_rl2);
        updateTv1 = (TextView) findViewById(R.id.update_tv1);
        updateRl.setOnClickListener(this::onClick);
        updateRl1.setOnClickListener(this::onClick);
        updateRl2.setOnClickListener(this::onClick);
        viewTopBack.setOnClickListener(this::onClick);

        getUserBroadcast = new getUserBroadcast();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("sends_user_name");
        registerReceiver(getUserBroadcast, intentFilter);


        try {
            UserEntity unique1 = DBManager.getInstance().getDaoSession().queryBuilder(UserEntity.class).unique();
            String user_img = unique1.getUser_img();
            Glide.with(this).load(user_img).circleCrop().into(updateHeadImg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            UserEntity unique2 = DBManager.getInstance().getDaoSession().queryBuilder(UserEntity.class).unique();
            if (unique2.getUser_sex().equals("1")) {
                updateTv1.setText("男");
            } else if (unique2.getUser_sex().equals("0")) {
                updateTv1.setText("女");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        updateUserPresenter = new UpdateUserPresenter(new UpdateUserModel(), this);


    }


    @Override
    public void inject() {
        DaggerUpdateUserComponent.builder().updateUserModules(new UpdateUserModules(this)).build().inject(this);
    }

    @Override
    public void initData() {
        UserEntity unique = null;
        try {
            unique = DBManager.getInstance().getDaoSession().queryBuilder(UserEntity.class).where(UserEntityDao.Properties.Id.eq(0)).unique();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String user_name = unique.getUser_name();
        updateTv.setText(user_name);
        setStatusBarColor(Color.WHITE);


        intent = new Intent();


    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.update_rl) {
            PopupWindow popupWindow = new PopupWindow();
            //加载布局文件
            View inflate = LayoutInflater.from(this).inflate(R.layout.pop_head_img, null);
            Button pop_head_img_cancel = inflate.findViewById(R.id.pop_head_img_cancel);
            Button pop_head_img_camera = inflate.findViewById(R.id.pop_head_img_camera);
            Button pop_head_img_album = inflate.findViewById(R.id.pop_head_img_album);
            pop_head_img_camera.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                    //使用FileProvider保存照片
                    path = "/sdcard/DCIM/Camera/" + creatCameraName();
                    Uri uriForFile = FileProvider.getUriForFile(UpdateUserActivity.this, "com.bw.lyc", new File(path));
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uriForFile);
                    startActivityForResult(intent, 102);
                    popupWindow.dismiss();
                }
            });
            pop_head_img_album.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_PICK);
                    intent.setType("image/*");
                    startActivityForResult(intent, 101);
                    popupWindow.dismiss();
                }
            });
            pop_head_img_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();
                }
            });
            popupWindow.setContentView(inflate);

            //设置宽高
            popupWindow.setWidth(ViewPager.LayoutParams.MATCH_PARENT);
            popupWindow.setHeight(ViewPager.LayoutParams.WRAP_CONTENT);
            popupWindow.setBackgroundDrawable(new BitmapDrawable());
            popupWindow.setAnimationStyle(R.style.Popupwindow);

            int[] location = new int[2];

            v.getLocationOnScreen(location);

            WindowManager.LayoutParams attributes = getWindow().getAttributes();
            attributes.alpha = 0.5f;
            getWindow().setAttributes(attributes);
            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    WindowManager.LayoutParams attributes = getWindow().getAttributes();
                    attributes.alpha = 1f;
                    getWindow().setAttributes(attributes);
                }
            });
            popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, -location[1]);
        } else if (id == R.id.update_rl1) {
            Intent intent = new Intent(UpdateUserActivity.this, UpdateNameActivity.class);
            startActivity(intent);
        } else if (id == R.id.update_rl2) {
            PopupWindow popupWindow = new PopupWindow();
            //加载布局文件
            View inflate = LayoutInflater.from(this).inflate(R.layout.pop_sex, null);
            Button pop_sex_cancel = inflate.findViewById(R.id.pop_sex_cancel);
            Button pop_sex_man = inflate.findViewById(R.id.pop_sex_man);
            Button pop_sex_woman = inflate.findViewById(R.id.pop_sex_woman);
            Button pop_sex_secrecy = inflate.findViewById(R.id.pop_sex_secrecy);

            pop_sex_secrecy.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    UserEntity unique = null;
                    try {
                        unique = DBManager.getInstance().getDaoSession().queryBuilder(UserEntity.class)
                                .where(UserEntityDao.Properties.Id.eq(0))
                                .unique();
                        if (unique != null) {
                            unique.setUser_sex("保密");
                        }
                        DBManager.getInstance().getDaoSession().update(unique);
                        LogUtils.json(DBManager.getInstance().getDaoSession().loadAll(UserEntity.class));
                        updateTv1.setText("保密");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                    popupWindow.dismiss();
                }
            });

            pop_sex_woman.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    UserEntity unique = null;
                    try {
                        unique = DBManager.getInstance().getDaoSession().queryBuilder(UserEntity.class)
                                .where(UserEntityDao.Properties.Id.eq(0))
                                .unique();
                        if (unique != null) {
                            unique.setUser_sex("0");
                        }
                        DBManager.getInstance().getDaoSession().update(unique);
                        LogUtils.json(DBManager.getInstance().getDaoSession().loadAll(UserEntity.class));
                        updateTv1.setText("女");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    popupWindow.dismiss();
                }
            });

            pop_sex_man.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    UserEntity unique = null;
                    try {
                        unique = DBManager.getInstance().getDaoSession().queryBuilder(UserEntity.class)
                                .where(UserEntityDao.Properties.Id.eq(0))
                                .unique();
                        if (unique != null) {
                            unique.setUser_sex("1");
                            unique.setUser_integral(1);
                        }
                        DBManager.getInstance().getDaoSession().update(unique);
                        LogUtils.json(DBManager.getInstance().getDaoSession().loadAll(UserEntity.class));
                        updateTv1.setText("男");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    popupWindow.dismiss();
                }
            });

            pop_sex_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();
                }
            });


            popupWindow.setContentView(inflate);
            popupWindow.setOutsideTouchable(true);

            //设置宽高
            popupWindow.setWidth(ViewPager.LayoutParams.MATCH_PARENT);
            popupWindow.setHeight(ViewPager.LayoutParams.WRAP_CONTENT);
            popupWindow.setBackgroundDrawable(new BitmapDrawable());
            popupWindow.setAnimationStyle(R.style.Popupwindow);

            int[] location = new int[2];

            v.getLocationOnScreen(location);

            WindowManager.LayoutParams attributes = getWindow().getAttributes();
            attributes.alpha = 0.5f;
            getWindow().setAttributes(attributes);
            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    WindowManager.LayoutParams attributes = getWindow().getAttributes();
                    attributes.alpha = 1f;
                    getWindow().setAttributes(attributes);
                }
            });
            popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, -location[1]);
        } else if (id == R.id.view_top_back) {
            try {
                UserEntity unique3 = DBManager.getInstance().getDaoSession().queryBuilder(UserEntity.class).where(UserEntityDao.Properties.Id.eq(0)).unique();

                updateUserPresenter.requestUpDataUser(new UserEntity(unique3.getUser_id(), unique3.getUser_phone(), unique3.getUser_pwd(), unique3.getUser_name(), unique3.getUser_sex(), unique3.getUser_img(), unique3.getUser_integral()));
            } catch (Exception e) {
                e.printStackTrace();
            }
            startPage(UpdateActivity.class);
            finish();
        }
    }

    public String creatCameraName() {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss");
        String format1 = format.format(date);
        return "IMG_" + format1 + ".jpg";
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101 && resultCode == Activity.RESULT_OK) {
            Uri data1 = data.getData();
            Cursor cursor = getContentResolver().query(data1, null, null, null, null);
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                }
            }
            String s = path;
            Glide.with(this).load(data1).transform(new CircleCrop()).into(updateHeadImg);


            try {
                UserEntity unique = DBManager.getInstance().getDaoSession().queryBuilder(UserEntity.class)
                        .where(UserEntityDao.Properties.Id.eq(0))
                        .unique();
                if (unique != null) {
                    unique.setUser_img(s);
                }
                DBManager.getInstance().getDaoSession().update(unique);
                LogUtils.json(DBManager.getInstance().getDaoSession().loadAll(UserEntity.class));

            } catch (Exception e) {
                e.printStackTrace();
            }
            updateUserPresenter.RequestUpload(path);
            intent.setAction("path");
            intent.putExtra("path", path);
            sendBroadcast(intent);

        } else if (requestCode == 102 && resultCode == Activity.RESULT_OK) {
            Glide.with(this).load(path).transform(new CircleCrop()).into(updateHeadImg);
            try {
                UserEntity unique = DBManager.getInstance().getDaoSession().queryBuilder(UserEntity.class)
                        .where(UserEntityDao.Properties.Id.eq(0))
                        .unique();
                if (unique != null) {
                    unique.setUser_img(path);
                }
                DBManager.getInstance().getDaoSession().update(unique);
                LogUtils.json(DBManager.getInstance().getDaoSession().loadAll(UserEntity.class));

            } catch (Exception e) {
                e.printStackTrace();
            }
            updateUserPresenter.RequestUpload(path);
            intent.setAction("path");
            intent.putExtra("path", path);
            sendBroadcast(intent);
        }
    }

    @Override
    public void refresh(BaseEntity baseEntity) {

    }

    class getUserBroadcast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("sends_user_name")) {
                String send_user_name = intent.getStringExtra("send_user_name");
                updateTv.setText("" + send_user_name);
                try {
                    UserEntity unique = DBManager.getInstance().getDaoSession().queryBuilder(UserEntity.class)
                            .where(UserEntityDao.Properties.Id.eq(0))
                            .unique();
                    if (unique != null) {
                        unique.setUser_name(send_user_name);
                    }
                    DBManager.getInstance().getDaoSession().update(unique);
                    LogUtils.json(DBManager.getInstance().getDaoSession().loadAll(UserEntity.class));

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(getUserBroadcast);

    }
}